package com.lemon.config;
import com.alibaba.cloud.ai.dashscope.api.DashScopeApi;
import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatModel;
import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.PromptChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.SafeGuardAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.client.advisor.api.Advisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.ai.openai.api.OpenAiApi;
import org.springframework.ai.embedding.EmbeddingModel;
import org.springframework.ai.vectorstore.SimpleVectorStore;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;

import java.util.List;
@Configuration
public class AiConfig {

    // 阿里云DashScope配置
    @Value("${spring.ai.dashscope.api-key:}")
    private String dashscopeApiKey;

    @Value("${spring.ai.dashscope.base-url:https://dashscope.aliyuncs.com/compatible-mode}")
    private String dashscopeBaseUrl;

    // OpenAI配置
    @Value("${spring.ai.openai.api-key:}")
    private String openaiApiKey;

    @Value("${spring.ai.openai.base-url:https://api.chatanywhere.tech}")
    private String openaiBaseUrl;

    // 添加一个初始化方法来检查配置
    @EventListener(ContextRefreshedEvent.class)
    public void init() {
        System.out.println("=== AiConfig 初始化 ===");
        System.out.println("DashScope API Key: " + (dashscopeApiKey != null ? "已配置(长度:" + dashscopeApiKey.length() + ")" : "未配置") + "api-key:" + dashscopeApiKey);
        System.out.println("DashScope Base URL: " + dashscopeBaseUrl);
        System.out.println("OpenAI API Key: " + (openaiApiKey != null && !openaiApiKey.isEmpty() ? "已配置" : "未配置") + "api-key:" + openaiApiKey);
        System.out.println("OpenAI Base URL: " + openaiBaseUrl);
    }

    // ==================== 默认ChatClient ====================
    @Bean
    public ChatClient chatClient(ChatClient.Builder builder,
                                 Advisor simpleLoggerAdvisor,
                                 Advisor promptChatMemoryAdvisor,
                                 Advisor safeGuardAdvisor) {
        return builder
                .defaultSystem(AIConstant.SYSTEM_ROLE)
                .defaultAdvisors((org.springframework.ai.chat.client.advisor.api.Advisor) simpleLoggerAdvisor, promptChatMemoryAdvisor, safeGuardAdvisor)
                .build();
    }

    // ==================== 角色专用ChatClient ====================
    @Bean("customerServiceChatClient")
    public ChatClient customerServiceChatClient(ChatClient.Builder builder,
                                                Advisor simpleLoggerAdvisor,
                                                Advisor promptChatMemoryAdvisor,
                                                Advisor safeGuardAdvisor) {
        return builder
                .defaultSystem(AIConstant.CUSTOMER_SERVICE_ROLE)
                .defaultAdvisors((org.springframework.ai.chat.client.advisor.api.Advisor) simpleLoggerAdvisor, promptChatMemoryAdvisor, safeGuardAdvisor)
                .build();
    }

    @Bean("dataAnalystChatClient")
    public ChatClient dataAnalystChatClient(ChatClient.Builder builder,
                                            Advisor simpleLoggerAdvisor,
                                            Advisor promptChatMemoryAdvisor,
                                            Advisor safeGuardAdvisor) {
        return builder
                .defaultSystem(AIConstant.DATA_ANALYST_ROLE)
                .defaultAdvisors((org.springframework.ai.chat.client.advisor.api.Advisor) simpleLoggerAdvisor, promptChatMemoryAdvisor, safeGuardAdvisor)
                .build();
    }

    // ==================== 阿里云Qwen模型专用ChatClient ====================
    // Qwen-Plus模型客户端
    @Bean("qwenPlusChatClient")
    public ChatClient qwenPlusChatClient(Advisor simpleLoggerAdvisor,
                                         Advisor promptChatMemoryAdvisor,
                                         Advisor safeGuardAdvisor) {

        // 创建阿里云DashScope API实例，使用配置的base-url和API Key
        DashScopeApi dashScopeApi = new DashScopeApi(dashscopeBaseUrl, dashscopeApiKey);

//        // 创建Qwen-Plus模型实例
//        DashScopeChatModel qwenPlusModel = new DashScopeChatModel(
//                dashScopeApi,
//                DashScopeChatOptions.builder()
//                        .withModel("qwen-plus")
//                        .build()
//        );
        // 创建DashScopeChatModel实例 - 使用更简单的方式
        DashScopeChatModel qwenPlusModel = new DashScopeChatModel(
                new DashScopeApi(dashscopeApiKey), // 只传API Key，使用默认base-url
                DashScopeChatOptions.builder()
                        .withModel("qwen-plus")
                        .build()
        );
        return ChatClient.builder(qwenPlusModel)
                .defaultSystem(AIConstant.SYSTEM_ROLE)
                .defaultAdvisors((org.springframework.ai.chat.client.advisor.api.Advisor) simpleLoggerAdvisor, promptChatMemoryAdvisor, safeGuardAdvisor)
                .build();
    }

    // Qwen-Turbo模型客户端
    @Bean("qwenTurboChatClient")
    @Primary
    public ChatClient qwenTurboChatClient(Advisor simpleLoggerAdvisor,
                                          Advisor promptChatMemoryAdvisor,
                                          Advisor safeGuardAdvisor) {
        // 创建阿里云DashScope API实例，使用配置的base-url和API Key
        DashScopeApi dashScopeApi = new DashScopeApi(dashscopeBaseUrl, dashscopeApiKey);
//
//        // 创建Qwen-Turbo模型实例
//        DashScopeChatModel qwenTurboModel = new DashScopeChatModel(
//                dashScopeApi,
//                DashScopeChatOptions.builder()
//                        .withModel("qwen-turbo")
//                        .build()
//        );
        // 创建DashScopeChatModel实例 - 使用更简单的方式
        DashScopeChatModel qwenTurboModel = new DashScopeChatModel(
                new DashScopeApi(dashscopeApiKey), // 只传API Key，使用默认base-url
                DashScopeChatOptions.builder()
                        .withModel("qwen-turbo")
                        .build()
        );

        return ChatClient.builder(qwenTurboModel)
                .defaultSystem(AIConstant.SYSTEM_ROLE)
                .defaultAdvisors((org.springframework.ai.chat.client.advisor.api.Advisor) simpleLoggerAdvisor, promptChatMemoryAdvisor, safeGuardAdvisor)
                .build();
    }

    // ==================== OpenAI模型专用ChatClient ====================
    // GPT-3.5-Turbo模型客户端
    @Bean("gpt35ChatClient")
    public ChatClient gpt35ChatClient(ChatClient.Builder defaultBuilder,
                                      Advisor simpleLoggerAdvisor,
                                      Advisor promptChatMemoryAdvisor,
                                      Advisor safeGuardAdvisor) {
        // 检查OpenAI配置是否可用
        if (openaiApiKey == null || openaiApiKey.isEmpty()) {
            System.out.println("OpenAI API Key is not configured, falling back to default chat client");
            // 使用默认builder作为回退
            return defaultBuilder
                    .defaultSystem(AIConstant.SYSTEM_ROLE)
                    .defaultAdvisors((org.springframework.ai.chat.client.advisor.api.Advisor) simpleLoggerAdvisor, promptChatMemoryAdvisor, safeGuardAdvisor)
                    .build();
        }

        // 使用配置的base-url和api-key创建OpenAI API实例
        OpenAiApi openAiApi = new OpenAiApi(openaiBaseUrl, openaiApiKey);

        OpenAiChatModel openAiChatModel = new OpenAiChatModel(openAiApi);

        // 使用OpenAI GPT-3.5-Turbo模型
        return ChatClient.builder(openAiChatModel)
                .defaultSystem(AIConstant.SYSTEM_ROLE)
                .defaultAdvisors((org.springframework.ai.chat.client.advisor.api.Advisor) simpleLoggerAdvisor, promptChatMemoryAdvisor, safeGuardAdvisor)
                .build();
    }

    // GPT-4模型客户端
    @Bean("gpt4ChatClient")
    public ChatClient gpt4ChatClient(ChatClient.Builder defaultBuilder,
                                     Advisor simpleLoggerAdvisor,
                                     Advisor promptChatMemoryAdvisor,
                                     Advisor safeGuardAdvisor) {
        // 检查OpenAI配置是否可用
        if (openaiApiKey == null || openaiApiKey.isEmpty()) {
            System.out.println("OpenAI API Key is not configured, falling back to default chat client");
            // 使用默认builder作为回退
            return defaultBuilder
                    .defaultSystem(AIConstant.SYSTEM_ROLE)
                    .defaultAdvisors(simpleLoggerAdvisor, promptChatMemoryAdvisor, safeGuardAdvisor)
                    .build();
        }

        // 使用配置的base-url和api-key创建OpenAI API实例
        OpenAiApi openAiApi = new OpenAiApi(openaiBaseUrl, openaiApiKey);

        OpenAiChatModel openAiChatModel = new OpenAiChatModel(openAiApi);

        // 使用OpenAI GPT-4模型
        return ChatClient.builder(openAiChatModel)
                .defaultSystem(AIConstant.SYSTEM_ROLE)
                .defaultAdvisors((org.springframework.ai.chat.client.advisor.api.Advisor) simpleLoggerAdvisor, promptChatMemoryAdvisor, safeGuardAdvisor)
                .build();
    }

    // ==================== 其他辅助Beans ====================
    @Bean
    public Advisor simpleLoggerAdvisor() {
        return new SimpleLoggerAdvisor();
    }

    @Bean
    public ChatMemory chatMemory() {
        return new InMemoryChatMemory();
    }

    @Bean
    public Advisor messageChatMemoryAdvisor(ChatMemory chatMemory) {
        return new MessageChatMemoryAdvisor(chatMemory);
    }

    @Bean
    public Advisor promptChatMemoryAdvisor(ChatMemory chatMemory) {
        return new PromptChatMemoryAdvisor(chatMemory);
    }

    @Bean
    public Advisor safeGuardAdvisor() {
        List<String> sensitiveWords = List.of("手机号", "微信号");
        return new SafeGuardAdvisor(
                sensitiveWords,
                "敏感词提示：请勿输入敏感词！",
                Advisor.DEFAULT_CHAT_MEMORY_PRECEDENCE_ORDER
        );
    }

    @Bean
    public VectorStore vectorStore(EmbeddingModel embeddingModel) {
        return SimpleVectorStore.builder(embeddingModel).build();
    }
}
